package com.socket;

import com.socket.handler.SerialPortHandler;
import gnu.io.*;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.TooManyListenersException;

public class SerialPortClient {

    public List<String> listAllPort() {
        List<String> portList = new ArrayList<>();

        Enumeration<CommPortIdentifier> portIdentifiers = CommPortIdentifier.getPortIdentifiers();
        String portName;
        while (portIdentifiers.hasMoreElements()) {
            portName = portIdentifiers.nextElement().getName();
            portList.add(portName);
            System.out.println("portName: " + portName);
        }

        System.out.println("listAllPort Size: " + portList.size());
        return portList;
    }

    public SerialPort open(String portName, int baudRate) {
        try {
            // 识别端口
            CommPortIdentifier commPortIdentifier = CommPortIdentifier.getPortIdentifier(portName);
            // 打开端口：端口名、超时时间
            CommPort commPort = commPortIdentifier.open(portName, 2000);
            if (commPort instanceof SerialPort) {
                System.out.println("open commPort: " + commPort.getName());

                SerialPort serialPort = (SerialPort) commPort;
                // 监听数据
                serialPort.addEventListener(new SerialPortHandler(serialPort));
                // 设置串口数据时间有效(可监听)
                serialPort.notifyOnDataAvailable(true);
                // 波特率、数据位、停止位、校验位
                serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                return serialPort;
            }
        } catch (NoSuchPortException e) {
            System.err.println("未找到串口");
            e.printStackTrace();
        } catch (PortInUseException e) {
            System.err.println("串口被占用");
            e.printStackTrace();
        } catch (TooManyListenersException e) {
            System.err.println("监听器过多");
            e.printStackTrace();
        } catch (UnsupportedCommOperationException e) {
            System.err.println("不支持串口操作");
            e.printStackTrace();
        }
        return null;
    }

    public void close(SerialPort serialPort) {
        if (null != serialPort) {
            serialPort.close();
        }
    }

    public static void main(String[] args) {
        SerialPortClient serialPortClient = new SerialPortClient();
        List<String> portList = serialPortClient.listAllPort();
        if (portList.size() > 0) {
            serialPortClient.open("COM3", 9600);
        }
    }
}
